import { DocumentEvents, DocumentObject, Types, Icon } from '@amcax/base';
import { userEvents } from '@app-cad/module';
import {
  FormContextType,
  RJSFSchema,
  StrictRJSFSchema,
  WidgetProps,
} from '@rjsf/utils';
import React, { useEffect, useState } from 'react';
import { MouseActionInput } from '../components/pick-input/mouse-action-input';

export default function GeomSetWidget<
  T = any,
  S extends StrictRJSFSchema = RJSFSchema,
  F extends FormContextType = any,
>({ onChange, uiSchema }: WidgetProps<T, S, F>) {
  const { placeholder } = uiSchema?.['ui:options'] || {};

  const [label, setLabel] = useState('');

  useEffect(() => {
    const onTreeObjectSelected = (doc: DocumentObject) => {
      if (doc.type === Types.GeomSet) {
        setLabel(doc.label);
        onChange?.(doc.dxid);
      } else {
        setLabel('');
        onChange?.('');
      }
    };
    userEvents.on(DocumentEvents.SELECT_TREE_OBJECT, onTreeObjectSelected);

    return () => {
      userEvents.off(DocumentEvents.SELECT_TREE_OBJECT, onTreeObjectSelected);
    };
  }, [onChange]);

  const handleClear = () => {
    setLabel('');
    onChange?.('');
  };

  return (
    <MouseActionInput
      active
      placeholder={placeholder}
    >
      {label ? (
        <div className='pick-input_base-select_selection'>
          <div>{label}</div>
          <div
            className='ml-auto'
            onClick={handleClear}
          >
            <Icon
              tabIndex={0}
              name='commons/close'
            />
          </div>
        </div>
      ) : null}
    </MouseActionInput>
  );
}
